import React, { memo, useCallback, useEffect, useState, useImperativeHandle, useRef, forwardRef, useMemo, useDebounce } from "react";
import MinAndMax from "@/components/MinAndMax";
import { Link, withRouter } from "react-router-dom";

import {
  handleDataLrc,
  addSongListAction,
  setCurrentSongDetail,
  playSongAction,
  addSongAction
} from "@/redux/actions";
import { songDetailwithIdsReq, getLrcWithIdReq } from "@/utils/api/user";
import {
  albumReq,
  commentAlbumReq,
  toplistNewcomerReq,
  artistAlbumReq,
  commentMusicReq,
  commentPlaylistReq,
  pubCommentReq
} from "@/utils/api/album";
import { getTime } from "@/utils/date";

import style from "./style.css";
import { connect } from "react-redux";
import { receiveSongList, addBrothernodechangetime } from "@/redux/actions";
import TopRedBorder from "@/components/TopRedBorder";
import GeciDetail from './GeciDetail'
import GeDanDetail from './GeDanDetail'
import ZjDetail from './GezjDetail'

const CommentList = memo(({ cms, noOpenup }) => {
  console.log(cms, "cms");
  return (
    <div className={style.clcontainer}>
      {cms
        ? cms.map((item) => (
          <div className={style.clItem} key={item.commentId}>
            <div className={style.clleft}>
              <img src={item.user.avatarUrl} alt="头像" />
            </div>
            <div className={style.clright}>
              <div className={style.clrighttop}>
                <span>{item.user.nickname}</span>
                {item.user.userType == 4 ? (
                  <img
                    src="https://p5.music.126.net/obj/wo3DlcOGw6DClTvDisK1/4874132307/4499/f228/d867/da64b9725e125943ad4e14e4c72d0884.png"
                    alt="网易小图标"
                    width="13"
                    width="13"
                  />
                ) : null}

                {item.user.vipType > 10 ? (
                  <img
                    src="//p6.music.126.net/obj/wo3DlcOGw6DClTvDisK1/4213923139/f08a/c6ea/10ee/f7e2deef21937a1042e370c47525c956.png"
                    alt="网易vip小图标"
                    width="35"
                    height="13"
                  />
                ) : null}
                <span>: {item.content}</span>
              </div>
              {item.beReplied.length > 0 ? (
                <div className={style.clrightcenter}>
                  <span>{item.beReplied[0].user.nickname}</span>
                  <img
                    src="https://p5.music.126.net/obj/wo3DlcOGw6DClTvDisK1/4874132307/4499/f228/d867/da64b9725e125943ad4e14e4c72d0884.png"
                    alt="网易小图标"
                  />
                  <span>: {item.beReplied[0].content}</span>
                </div>
              ) : null}
              <div className={style.clrightbottom}>
                <span style={{ color: "#acacac" }}>{getTime(item.time, 3)}</span>
                <div onClick={() => noOpenup()}>
                  <img
                    src={require("./svgs/dianzan.svg").default}
                    alt="点赞"
                  />
                  <span>{item.likedCount || 0}</span>
                  <a> | 回复</a>
                </div>
              </div>
            </div>
          </div>
        ))
        : null}
    </div>
  );
});

const Comment = memo(forwardRef((props, ref) => {
  const { comments, hotcomments, total, songType, resourceId, commentId, noOpenup } = props;
  const [commentContent, setCommentContent] = useState('')

  const commentRef = useRef(null);
  useImperativeHandle(ref, () => commentRef.current);


  const publishComment = useCallback(async (type = 1) => {
    if (commentContent === '') {
      return alert('请输入内容')
    }
    let data
    if (type == 1) {
      // 发送评论
      data = {
        t: 1,
        type: songType,
        id: resourceId,
        content: commentContent,
        commentId: commentId || ''
      }
    } else {
      // 回复评论

    }
    console.log(data, 'data')
    const res = await pubCommentReq(data)
    if (res.data.code === 200) {
      alert('发送成功')
    }
  }, [commentContent])

  if (!comments || !hotcomments) {
    return <div>Loading...</div>;
  }

  return (
    <div className={style.commentDetail} ref={commentRef}>
      <div className={style.zjBottomTitle}>
        <div>评论</div>
        <div>共{total}条评论</div>
      </div>
      <div className={style.cmuserinfo}>
        <div className={style.cmavatar}></div>
        <div className={style.cmright}>
          <textarea placeholder="评论" type="textarea" value={commentContent} onChange={e => setCommentContent(e.target.value)} />
          <div className={style.cmrightbottom}>
            <div className={style.cmbottomleft} onClick={() => noOpenup()}>
              <img src={require("./svgs/smile.svg").default} alt="笑脸" />
              <img src={require("./svgs/aite.svg").default} alt="@" />
            </div>
            <div className={style.cmbottomright}>
              <span>140</span>
              <button style={{ marginLeft: "10px" }} onClick={() => publishComment(1)}>评论</button>
            </div>
          </div>
        </div>
      </div>
      <div className={style.commentList}>
        <div className={style.cltitle}>精彩评论（{hotcomments.length}）</div>
        {/* {getCommentList(comments)} */}
        <CommentList cms={hotcomments} noOpenup={noOpenup} />
      </div>
      <div className={style.commentList}>
        <div className={style.cltitle}>最新评论（{comments.length}）</div>
        <CommentList cms={comments} noOpenup={noOpenup} />
        {/* {getCommentList(hotComments)} */}
      </div>
    </div>
  )
}));

const RightOther = memo(({ authorid }) => {
  const [newperson, setNewperson] = useState([]);
  const [hotAlbums, setHotalbums] = useState([]);

  useEffect(() => {
    const getData = async () => {
      const res = await toplistNewcomerReq({ limit: 8 });
      if (res.data.code === 200) {
        setNewperson(res.data.data.list);
      }
      const res2 = await artistAlbumReq({ id: authorid });
      if (res2.data.code === 200) {
        if (res2.data.hotAlbums.length > 5) {
          let list = res2.data.hotAlbums.splice(0, 5);
          console.log(list, "list");
          setHotalbums(list);
        } else {
          setHotalbums(res2.data.hotAlbums);
        }
      }
    };
    getData();
  }, []);

  const getItemList = useCallback(
    (index) => {
      switch (index) {
        case 1:
          return newperson.map((item) => (
            <li className={style.oitemItem} key={item.id}>
              <img src={item.avatarUrl} alt={"头像" + item.id} />
            </li>
          ));
        case 2:
          return hotAlbums.map((item, index) => (
            <li key={index}>
              <Link to={`/song/${item.id}/2`} className={style.oitemItemTwo}>
                <div className={style.itemtwoleft}>
                  <img src={item.blurPicUrl} alt={"头像" + item.id} />
                </div>
                <div className={style.itemtworight}>
                  <a>{item.name}</a>
                  <h5>{getTime(item.publishTime)}</h5>
                </div>
              </Link>
            </li>
          ));
      }
    },
    [newperson, hotAlbums]
  );

  return (
    <div className={style.detailRight}>
      <div className={style.oitem}>
        <div className={style.oitemtitle}>喜欢这张专辑的人</div>
        <ul className={style.oitemsListone}>{getItemList(1)}</ul>
      </div>
      <div className={style.oitem}>
        <div className={style.oitemtitle}>
          <span>Ta的其他热门专辑</span>
          <a>全部</a>
        </div>
        <ul className={style.oitemsListtwo}>{getItemList(2)}</ul>
      </div>
      <div className={style.oitem}>
        <div className={style.oitemtitle}>网易云音乐多端下载</div>
        <a href="https://music.163.com/#/download" target="_block">
          <ul className={style.download}>
            <li>
              <a href="#"></a>
            </li>
            <li>
              <a href="#"></a>
            </li>
            <li>
              <a href="#"></a>
            </li>
          </ul>
        </a>
        <div style={{ color: "#999", fontSize: "12px" }}>
          同步歌单，随时畅听320k好音乐
        </div>
      </div>
    </div>
  );
});



function SongDetail(props) {
  const {
    match,
    receiveSongListFun,
    addSongList,
    setCurrentSong,
    history,
    addBrothernodechangetimeFun,
    playSong,
    addSong
  } = props;
  const [songDetail, setSongDetail] = useState(null);
  const [lrcData, setLrcData] = useState(null);
  const [album, setAlbum] = useState(null);
  const [songs, setSongs] = useState([]);
  const [comments, setComments] = useState(null);
  const [hotcomments, setHotcomments] = useState(null);
  const [total, setTotal] = useState(0);
  const [authorid, setAuthorid] = useState("");
  const [currentType, setCurrentType] = useState(match.params.type);
  const [resourceId, setResourceId] = useState(match.params.id)
  const [songType, setSongType] = useState('')
  const commentRef = useRef(null);


  useEffect(() => {
    if (currentType == 2 && album) {
      setAuthorid(album.artist.id);
    } else if (currentType == 1 && songDetail) {
      setAuthorid(songDetail.ar[0].id);
    } else if (currentType == 3) {
      // setAuthorid('match.params.id')
    }
  }, [history.location.pathname]);

  useEffect(() => {
    console.log(currentType, ".params.type");
    let getData;
    if (currentType == 1) {
      console.log(currentType, "111");
      let data = { id: match.params.id };
      getData = async () => {
        const res = await songDetailwithIdsReq({ ids: match.params.id });
        if (res.data.code === 200) {
          setSongDetail(res.data.songs[0]);
        }

        const resTwo = await getLrcWithIdReq(data);
        if (resTwo.data.code === 200) {
          let lrcArr = handleDataLrc(false, resTwo.data.lrc.lyric);
          setLrcData(lrcArr);
        }

        const resthree = await commentMusicReq(data);
        if (resthree.data.code === 200) {
          setComments(resthree.data.comments);
          setHotcomments(resthree.data.hotComments);
          setTotal(resthree.data.total);
        }
      };
      setSongType(0)
    } else if (currentType == 2) {
      console.log(currentType, "222222");
      getData = async () => {
        let data = {
          id: match.params.id,
        };
        const res = await albumReq(data);
        console.log(res.data, "res.data");
        if (res.data.code === 200) {
          setAlbum(res.data.album);
          setSongs(res.data.songs);
        }
        const restwo = await commentAlbumReq(data);
        if (restwo.data.code === 200) {
          setComments(restwo.data.comments);
          setHotcomments(restwo.data.hotComments);
          setTotal(restwo.data.total);
        }
      };
      setSongType(3)
    } else if (currentType == 3) {
      getData = async () => {
        const resTwo = await commentPlaylistReq({ id: match.params.id });
        if (resTwo.data.code === 200) {
          setComments(resTwo.data.comments);
          setHotcomments(resTwo.data.hotComments);
          setTotal(resTwo.data.total);
          setSongDetail()
        }
      };
      setSongType(2)
    }
    getData();
  }, [history.location.pathname, authorid]);

  const playSong2 = useCallback((id, type = 2, songArr = []) => {
    // 直接接收一个ids : String 加入歌单 播放最后一首
    if (type == 1) {
      // 播放全部
      let idarr = []
      songArr.forEach(item => {
        idarr.push(item.id)
      });
      let ids = idarr.join(',')
      console.log(ids, 'ids')
      addSongList({ ids })
      let id = ''
      if (ids && ids.length) {
        let idarr = ids.split(',')
        id = idarr[idarr.length - 1]
      } else {
        id = ids
      }
      console.log(id, 'id')
      setCurrentSong(id)
      addBrothernodechangetimeFun()
    } else {
      addSongList({ ids: id })
      setCurrentSong(id)
      addBrothernodechangetimeFun()
    }
  }, []);

  const addSong2 = useCallback((ids, type = 2, songArr = []) => {
    // 如果type == 2 songArr 是必须的参数
    // 如果type == 1 直接姜ids 添加歌单
    if (type == 1) {
      // 接收ids: String 直接加入歌单
      let idarr = []
      songArr.forEach(item => {
        idarr.push(item.id)
      });
      let idstr = idarr.join(',')

      addSongList({ ids: idstr });
    } else {
      addSongList({ ids: ids });
    }
  }, []);

  const noOpenup = useCallback(() => {
    alert('暂未开放!')
  }, [])

  const scrollComment = useCallback(() => {
    let height = commentRef.current.offsetTop
    document.documentElement.scrollTop = height
  })

  if (currentType == 2 && !album) {
    return <div>Loading...</div>;
  }

  if (currentType == 1 && !songDetail) {
    return <div>Loading...</div>;
  }

  return (
    <>
      <TopRedBorder />
      <MinAndMax>
        <div className={style.songdetail}>
          <div className={style.detailleft}>
            {currentType == 1 ? (
              <GeciDetail
                total={total}
                song={songDetail}
                lrcData={lrcData}
                addSong={addSong}
                playSong={playSong}
                noOpenup={noOpenup}
                scrollComment={scrollComment}
              />
            ) : null}
            {currentType == 2 ? (
              <ZjDetail
                album={album}
                songs={songs}
                receiveSongListFun={receiveSongListFun}
                addSong={addSong}
                playSong={playSong}
                noOpenup={noOpenup}
                scrollComment={scrollComment}
              />
            ) : null}
            {currentType == 3 ? (
              <GeDanDetail total={total}
                match={match}
                addSong={addSong}
                noOpenup={noOpenup}
                scrollComment={scrollComment}
                playSong={playSong} />
            ) : null}
            <Comment
              comments={comments}
              hotcomments={hotcomments}
              total={total}
              ref={commentRef}
              resourceId={resourceId}
              songType={songType}
              noOpenup={noOpenup}
            />
          </div>
          <RightOther authorid={authorid} />
        </div>
      </MinAndMax>
    </>
  );
}

const mState = (state) => {
  return {};
};
const mDispatch = (dispatch) => {
  return {
    receiveSongListFun: (data) => {
      dispatch(receiveSongList(data));
    },
    addSongList: (data) => {
      dispatch(addSongListAction(data));
    },
    setCurrentSong: (data) => {
      console.log(data, "setCurrentSong");
      dispatch(setCurrentSongDetail(data));
    },
    addBrothernodechangetimeFun: () => {
      dispatch(addBrothernodechangetime())
    },
    playSong: (...arg) => {
      dispatch(playSongAction(...arg))
    },
    addSong: (...arg) => {
      dispatch(addSongAction(...arg))
    }
  };
};
export default withRouter(connect(mState, mDispatch)(SongDetail));
